package com.gl.common.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * 阿里云oss工具类
 *
 * @author zhiping
 */
@Component
public class AliyunOssUtil {

    @Value("${ali.oss.endpoint}")
    private String endPoint;
    @Value("${ali.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${ali.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ali.oss.bucket}")
    private String bucketName;


    /**
     * oss 工具客户端
     */
    private  OSSClient ossClient = null;

    /**
     * 上传文件至阿里云 OSS
     *
     * @param file 待上传文件
     *             返回访问的全路径
     */
    public String uploadFileToOss(MultipartFile file) {
        // 初始化oss
        initOSS(endPoint, accessKeyId, accessKeySecret);
        String visitUrl = null;
        try {
            // 获取文件名
            String extName =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            String today = DateUtil.format(new Date(), "yyyy/MM/dd");
            String fileDir = today;

            String fileRelName = fileDir + "/" + IdUtil.simpleUUID() + extName;
            // 上传至oss
            PutObjectResult result = ossClient.putObject(bucketName, fileRelName, file.getInputStream());
            if (result != null) {
                System.out.println("OSS文件上传成功------");
            }
            // 拼接访问路径
            visitUrl = "https://" + bucketName + "." + endPoint + "/" + fileRelName;
        } catch (IOException e) {
            // log.error(e.getMessage(), e);
            System.out.println(e.getMessage());
            return null;
        }
        return visitUrl;
    }

    /**
     * 删除文件
     *
     * @param fileName
     */
    public void deleteFileToOss(String fileName) {
        ossClient.deleteObject(bucketName, fileName);
    }

    /**
     * 初始化 oss 客户端
     *
     * @return
     */
    private OSSClient initOSS(String endpoint, String accessKeyId, String accessKeySecret) {
        if (ossClient == null) {
            synchronized (OSSClient.class) {
                if (ossClient == null) {
                    ossClient = new OSSClient(endpoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), new ClientConfiguration());
                    // 设置权限(公开读)
                    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                }
            }
        }
        return ossClient;
    }

}
